from flask import Blueprint,request,render_template

#管理页面
mg = Blueprint('manage',__name__)
import pymysql

conn = pymysql.connect(
    host = '127.0.0.1',
    user ='root',
    password = '123456',
    db='orderingsystem',
    charset='utf8'
)

@mg.route('/getRegisterRequest')
def getRegisterRequest():#注册管理
    user = request.args.get('userName')
    pwd = request.args.get('password')
    rpwd = request.args.get("rpassword")#从页面获取输入的确认密码
    if user == '' or pwd == '':
        return '不能为空!'
    cursor = conn.cursor()
    sql = "select user_name from user where user_name='" + user + "' " #查询数据库中是否存在此用户
    if(pwd==rpwd):#判断密码与确认密码是否相同
        try:
            cursor.execute(sql)
            result = cursor.fetchall()
            if len(result) > 1:  # 若存在，提示'该用户已存在，请换号注册'
                return '该用户已存在，请换号注册'
            else:#插入数据到数据库中
                cursor.execute('INSERT INTO user(user_name,pwd) VALUES(%s,%s)', (user, pwd))
                conn.commit()
                return '注册成功'
            conn.commit()
        except:
            # 如果发生错误则回滚
            traceback.print_exc()
            conn.rollback()
    else:
        return '两次密码输入不一致'

#登录管理
@mg.route('/login')
def getLoginRequest():#登录管理
    user = request.args.get('userName')
    pwd = request.args.get('password')
    cursor = conn.cursor()
    # SQL 查询语句
    sql = "select * from user where user_name='" + user + "' and pwd='" + pwd + "'"#根据输入的账号密码查询数据库
    try:
        # 执行sql语句
        cursor.execute(sql)
        results = cursor.fetchall()
        if len(results) == 1:#查询到存在该用户跳转到index.html
            return render_template('index.html')
        else:
            return '用户名或密码不正确'
        # 提交到数据库执行
        conn.commit()
    except:
        # 如果发生错误则回滚
        traceback.print_exc()
        conn.rollback()
    # 关闭数据库连接
    conn.close()
